package com.kfm.kfmchat.listener;

import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import okhttp3.Response;
import okhttp3.sse.EventSource;
import okhttp3.sse.EventSourceListener;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.io.IOException;

@Slf4j
@Setter
public class ChatGPTEventSourceListener extends EventSourceListener {

    private SseEmitter sseEmitter;

    // eventSource 关闭
    @Override
    public void onClosed(@NotNull EventSource eventSource) {
        super.onClosed(eventSource);
    }

    // eventSource 发生变化
    @Override
    public void onEvent(@NotNull EventSource eventSource, @Nullable String id, @Nullable String type, @NotNull String data) {
        // data 就是 响应的内容
        super.onEvent(eventSource, id, type, data);
        // 向前端发送数据
        try {
            sseEmitter.send(SseEmitter.event().id("YCDL").data(data));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    // eventSource 失败
    @Override
    public void onFailure(@NotNull EventSource eventSource, @Nullable Throwable t, @Nullable Response response) {
        super.onFailure(eventSource, t, response);
    }

    // eventSource 打开
    @Override
    public void onOpen(@NotNull EventSource eventSource, @NotNull Response response) {
        super.onOpen(eventSource, response);
    }
}
